import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/store/user'

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue'),
    meta: {
      title: '登录',
      requiresAuth: false
    }
  },


  {
    path: '/',
    component: () => import('@/layouts/MainLayout.vue'),
    meta: { requiresAuth: true },
    redirect: '/dashboard',
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('@/views/Dashboard.vue'),
        meta: {
          title: '概览仪表板',
          requiresAuth: true
        }
      },
      {
        path: 'users/manage',
        name: 'EcommerceUserManagement',
        component: () => import('@/views/data/Manage.vue'),
        meta: {
          title: '用户管理',
          requiresAuth: true
        }
      },
      {
        path: 'analysis',
        name: 'AnalysisOverview',
        component: () => import('@/views/analysis/Overview.vue'),
        meta: {
          title: '数据分析',
          requiresAuth: true
        }
      },
      {
        path: 'analysis/profile/basic',
        name: 'BasicProfile',
        component: () => import('@/views/analysis/profile/Basic.vue'),
        meta: {
          title: '基础画像',
          requiresAuth: true
        }
      },
      {
        path: 'analysis/profile/behavior',
        name: 'BehaviorProfile',
        component: () => import('@/views/analysis/profile/Behavior.vue'),
        meta: {
          title: '行为画像',
          requiresAuth: true
        }
      },
      {
        path: 'analysis/profile/consumption',
        name: 'ConsumptionProfile',
        component: () => import('@/views/analysis/profile/Consumption.vue'),
        meta: {
          title: '消费画像',
          requiresAuth: true
        }
      },
      {
        path: 'analysis/segmentation',
        name: 'UserSegmentation',
        component: () => import('@/views/analysis/Segmentation.vue'),
        meta: {
          title: '用户分群',
          requiresAuth: true
        }
      },
      {
        path: 'analysis/test',
        name: 'AnalysisTest',
        component: () => import('@/views/analysis/TestAnalysis.vue'),
        meta: {
          title: 'API测试',
          requiresAuth: true
        }
      },
      {
        path: 'profile',
        name: 'Profile',
        component: () => import('@/views/Profile.vue'),
        meta: {
          title: '个人资料',
          requiresAuth: true
        }
      },
      {
        path: 'settings',
        name: 'Settings',
        component: () => import('@/views/Settings.vue'),
        meta: {
          title: '系统设置',
          requiresAuth: true
        }
      },
      {
        path: 'debug-user',
        name: 'UserInfoDebug',
        component: () => import('@/views/UserInfoDebug.vue'),
        meta: {
          title: '用户信息调试',
          requiresAuth: true
        }
      },
      // 预测分析模块
      {
        path: 'prediction/churn',
        name: 'ChurnPrediction',
        component: () => import('@/views/prediction/Churn.vue'),
        meta: {
          title: '流失预测',
          requiresAuth: true
        }
      },
      {
        path: 'prediction/purchase',
        name: 'PurchasePrediction',
        component: () => import('@/views/prediction/Purchase.vue'),
        meta: {
          title: '购买预测',
          requiresAuth: true
        }
      },
      // 推荐系统模块
      {
        path: 'recommendation',
        name: 'Recommendation',
        component: () => import('@/views/Recommendation.vue'),
        meta: {
          title: '推荐系统',
          requiresAuth: true
        }
      },
      // 系统管理模块
      {
        path: 'system/page-structure',
        name: 'PageStructure',
        component: () => import('@/views/system/PageStructure.vue'),
        meta: {
          title: '页面结构',
          requiresAuth: true
        }
      },
      {
        path: 'system/monitor',
        name: 'SystemMonitor',
        component: () => import('@/views/system/SystemMonitor.vue'),
        meta: {
          title: '系统监控',
          requiresAuth: true
        }
      },
      {
        path: 'system/users',
        name: 'UserManagement',
        component: () => import('@/views/system/UserManagement.vue'),
        meta: {
          title: '用户管理',
          requiresAuth: true
        }
      },
      {
        path: 'system/permissions',
        name: 'PermissionManagement',
        component: () => import('@/views/system/PermissionManagement.vue'),
        meta: {
          title: '权限管理',
          requiresAuth: true
        }
      },
      // 模型管理模块
      {
        path: 'models/browser',
        name: 'ModelBrowser',
        component: () => import('@/views/models/ModelBrowser.vue'),
        meta: {
          title: '模型浏览',
          requiresAuth: true
        }
      },
      {
        path: 'models/evaluate/:id?',
        name: 'ModelEvaluation',
        component: () => import('@/views/models/ModelEvaluation.vue'),
        meta: {
          title: '模型评估',
          requiresAuth: true
        }
      },
      {
        path: 'models/train/:id?',
        name: 'ModelTraining',
        component: () => import('@/views/models/SimpleModelTraining.vue'),
        meta: {
          title: '模型训练',
          requiresAuth: true
        }
      },
      // 可视化大屏模块（在主布局中显示）
      {
        path: 'datav/monitor',
        name: 'RealTimeMonitor',
        component: () => import('@/datav/Monitor.vue'),
        meta: {
          title: '实时监控大屏',
          requiresAuth: true
        }
      },
      {
        path: 'datav/user-analysis',
        name: 'UserAnalysisScreen',
        component: () => import('@/datav/UserAnalysis.vue'),
        meta: {
          title: '用户分析大屏',
          requiresAuth: true
        }
      },
      {
        path: 'datav/sales-analysis',
        name: 'SalesAnalysisScreen',
        component: () => import('@/datav/SalesAnalysis.vue'),
        meta: {
          title: '销售分析大屏',
          requiresAuth: true
        }
      },
      {
        path: 'datav/operation',
        name: 'OperationScreen',
        component: () => import('@/datav/Operation.vue'),
        meta: {
          title: '运营决策大屏',
          requiresAuth: true
        }
      }
    ]
  },
  // 全屏模式路由（不包含主布局）
  {
    path: '/fullscreen',
    name: 'FullscreenDataV',
    meta: { requiresAuth: true },
    children: [
      {
        path: 'monitor',
        name: 'FullscreenMonitor',
        component: () => import('@/datav/Monitor.vue'),
        meta: {
          title: '实时监控大屏',
          fullscreen: true,
          requiresAuth: true
        }
      },
      {
        path: 'user-analysis',
        name: 'FullscreenUserAnalysis',
        component: () => import('@/datav/UserAnalysis.vue'),
        meta: {
          title: '用户分析大屏',
          fullscreen: true,
          requiresAuth: true
        }
      },
      {
        path: 'sales-analysis',
        name: 'FullscreenSalesAnalysis',
        component: () => import('@/datav/SalesAnalysis.vue'),
        meta: {
          title: '销售分析大屏',
          fullscreen: true,
          requiresAuth: true
        }
      },
      {
        path: 'operation',
        name: 'FullscreenOperation',
        component: () => import('@/datav/Operation.vue'),
        meta: {
          title: '运营决策大屏',
          fullscreen: true,
          requiresAuth: true
        }
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  
  // 设置页面标题
  if (to.meta.title) {
    document.title = `${to.meta.title} - 电商用户行为分析系统`
  }
  
  // 检查是否需要认证
  if (to.meta.requiresAuth) {
    if (userStore.isAuthenticated) {
      // 如果已登录但没有用户信息，尝试获取
      if (!userStore.userInfo) {
        userStore.getUserInfo().catch(() => {
          // 如果获取用户信息失败，可能token已过期，跳转到登录页
          next('/login')
          return
        })
      }
      next()
    } else {
      next('/login')
    }
  } else {
    // 如果已登录且访问登录页，重定向到仪表板
    if (to.path === '/login' && userStore.isAuthenticated) {
      next('/dashboard')
    } else {
      next()
    }
  }
})

export default router
